<template>
  <el-form :model="formModel">
    <el-container>
      <el-header style="margin-top: 30px">
        <el-row class="top-bar">
          <el-col :span="2">
            <a class="homeContentStyle" @click="gotoHomePage" style="color: black;cursor: pointer;">
              首页
            </a>
          </el-col>
          <el-col :span="16">
            <div>
              <el-form-item>
                <el-input v-model="formModel.model.title" placeholder="请填写问题标题"/>
              </el-form-item>
              <el-form-item>
                <el-input v-model="formModel.model.userId" v-if="false" type="hidden"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="2">
            <div style="margin-left: 20px">
              <el-form-item>
                <el-button type="primary" @click="saveArticleDraft" class="saveDraftButton">保存草稿</el-button>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="2">
            <div style="margin-left: 20px">
              <el-form-item>
                <el-button type="primary" @click="saveArticle" style="border-radius: 10px">重新发布</el-button>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="2">
            <Avatar class="avatarStyle"/>
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-form-item>
          <v-md-editor
              :disabled-menus="[]"
              @upload-image="handleUploadImage"
              v-model="formModel.model.content"
              height="400px">
          </v-md-editor>
        </el-form-item>
        <div class="flex gap-2">
          <el-tag
              v-for="tag in dynamicTags"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
              v-if="inputVisible"
              ref="InputRef"
              v-model="inputValue"
              class="w-20"
              size="small"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">
            + 新建标签
          </el-button>
        </div>
      </el-main>
    </el-container>
  </el-form>
  <Footer/>
</template>

<script setup>
import {reactive, getCurrentInstance, nextTick, ref, onMounted} from 'vue'
import {ElInput} from 'element-plus'
import {useRouter, useRoute} from 'vue-router'
import {ListArticleById, SaveArticle,SaveArticleDraft} from "@/api/member/article.js";
import {useUserinfo} from "@/components/hooks/useUserinfo.js";
import Avatar from '@/components/Avatar/Avatar.vue'
import Footer from '@/components/Footer/Footer.vue'
import {UploadArticleImage} from "@/api/member/upload.js";


const router = useRouter()
const {proxy: ctx} = getCurrentInstance()
const {userinfo} = useUserinfo()
const formModel = reactive({
  model: {
    id: '',
    userId: userinfo.value.id,
    title: '',
    content: '',
    tags: '',
  },
})



/** 文章图片上传 **/
const handleUploadImage = async (event, insertImage, files) => {
  // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
  // console.log(files);
  let formData = new FormData();
  formData.append("file", files[0])
  formData.append("userId", userinfo.value.id)
  const {code, data, msg} = await UploadArticleImage(formData)
  try {
    if (code === 200) {
      ctx.$message.success(msg)
      // console.log("data: " ,data.value)
      insertImage({
        url: data.imgUrl,
        desc: data.desc,
        // width: 'auto',
        // height: 'auto',
      });
    } else {
      ctx.$message.error(msg)
    }
  } catch (error) {
    console.log("error: ",error)
    ctx.$message.error(error)
  }

}


/**====动态生成标签=====*/
const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref('')
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}


const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    if (InputRef.value && InputRef.value.input) {
      InputRef.value.input.focus();
    }
  })
}


const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
/**================*/


/**=====获取文章数据===========*/
const route = useRoute()
const articleId = route.params.id
const article = ref(null);
const tags = ref([])
const fetchArticleById = async () => {
  try {
    const params={
      id: articleId,
      userId: userinfo.value.id
    }
    const {code, data, msg} = await ListArticleById(params);
    if (code === 200) {
      article.value = data;
      if (article.value.tags === null || article.value.tags === '') {
        tags.value = null;
      } else {
        tags.value = article.value.tags?.split(",");
        dynamicTags.value = tags.value
      }
      formModel.model.title = article.value.title
      formModel.model.content = article.value.content
      formModel.model.tags = article.value.tags
    } else {
      ctx.$message.error(msg)
    }
  } catch (error) {
    ctx.$message.error(error)
  }
}
/**=======================*/


/**=====发布文章===========*/
const saveArticle = async () => {
  formModel.model.tags = dynamicTags.value.toString()
  formModel.model.id = articleId
  console.log(formModel.model.userId)
  if (formModel.model.userId == null) {
    ctx.$message.error("请登录")
    return
  }
  const {code, msg} = await SaveArticle(formModel.model)
  if (code === 200) {
    ctx.$message.success(msg)
    router.push('/home')
  } else {
    ctx.$message.error(msg)
  }
}
/**=======================*/


/**====保存草稿====**/
const saveArticleDraft = async () => {
  formModel.model.tags = dynamicTags.value.toString();
  formModel.model.id = articleId
  console.log(formModel.model.userId)
  if (formModel.model.userId == null) {
    ctx.$message.error("请登录")
    return
  }
  const {code, msg} = await SaveArticleDraft(formModel.model)
  if (code === 200) {
    ctx.$message.success(msg)
    router.push('/goToMySpacePage')
  } else {
    ctx.$message.error(msg)
  }

}


// 跳转到主页
const gotoHomePage = () => {
  router.push('/home')
}


onMounted(() => {
  fetchArticleById();
})


</script>

<style scoped>
.top-bar {
  text-align: center;
}

.homeContentStyle {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 5px;
}

/** 头像样式 */
.avatarStyle {
  display: flex;
  align-items: center;
  justify-content: center;
}

/** 保存草稿样式*/
.saveDraftButton {
  border-radius: 10px;
  border: none;
  background-color: yellow;
  color: black;
}

</style>